import React, { useEffect, useState } from 'react';
import GopherProps from '../objects/internal/GopherProps';
import { Select } from 'antd';

const {Option} = Select;

export interface AsyncRoleSelectorProps extends GopherProps {
	value?: string;

	onValueChange?: (x: string) => void;
}

export default function AsyncRoleSelector(props: AsyncRoleSelectorProps) {
	const [loading, setLoading] = useState(true);
	const [roles, setRoles] = useState<Record<string, string>>({});
	const [value, setValue] = useState(props.value);

	useEffect(() => {
		props.gopher.getFriendlyRoleNames().then(xs => {
			setRoles(xs);
			setLoading(false);
		});
	}, [props.gopher]);

	useEffect(() => {
		setValue(props.value);
	}, [props.value]);

	return (
		<Select loading={loading} value={value} onChange={x => { setValue(x as string); if (props.onValueChange) { props.onValueChange(x as string || '') }}}>{Object.keys(roles).map((name, index) => <Option
			key={index} value={name}>{roles[name]}</Option>)}</Select>
	);
}
